(function($){
	
	function ClearArray(arr){
		arr2=new Array();
		$.each(arr, function(i,n) {
			if($.trim(n)!=""){
				arr2[i]=n;
			}
		});
		return arr2;
	}
	
	var defaults={
		fileInputName:'file',
		pictureInputName:'picture',
		type:'image',
		initValue:[],
		isMulti:false,
		uploadPath:null,
		callback:null
	};

	var imageEdit = null;
	var type=null;
	var percentlayer=null;
	
	$.fn.extend({
		upload:function(options){
			var thisObj = $(this);
			var opts=$.extend(defaults,options);
			var fileInputName = opts.fileInputName;
			var pictureInputName = opts.pictureInputName;
			var type = opts.type;
			var initValue = thisObj.attr('attr-value').split(',');
			var isMulti = opts.isMulti;
			var uploadPath = opts.uploadPath;
			var callback = opts.callback;
			
			if(type=='image' || type=='face'){
				var uploadContainer = $('<div class="myupload_image_container"></div>');	
			}else if(type=='file' || type=='audio' || type=='video'){
				var uploadContainer = $('<div class="myupload_file_container"></div>');
			}
			
			initValue=ClearArray(initValue);
			
			thisObj.html('');
			
			thisObj.append(uploadContainer);
			
			if(type=='file' || type=='audio' || type=='video'){
				var uploadButton = $('<div class="table_uploader" role="myupload-file-input-btn"><a href="javascript:;" class="btn btn-success btn-sm"><i class="icon-upload-alt"></i> 点击上传</a></div>');
			}else{
				var uploadButton = $('<div class="table_uploader" role="myupload-file-input-btn"><a href="javascript:;" class="image_upload_btn">点击上传</a></div>');
			}

        	
			if(initValue.length >= 1 && !isMulti) {//如果有初始值并且是单图模式则隐藏上传按钮
				uploadButton.hide();
			}
			
			uploadContainer.append(uploadButton);
			if(isMulti){
				var uploadForm = $('<form class="uploader_frm" action="#" enctype="multipart/form-data" method="post" role="myupload-file-form"><input type="file" name="'+fileInputName+'[]" role="myupload-file-input" accept="*" multiple="true" style="display:none;"/><input type="text" style="display:none" name="type" value="'+type+'" /></form>');
			}else{
				var uploadForm = $('<form class="uploader_frm" action="#" enctype="multipart/form-data" method="post" role="myupload-file-form"><input type="file" name="'+fileInputName+'" role="myupload-file-input" accept="*" style="display:none;"/><input type="text" style="display:none" name="type" value="'+type+'" /></form>');
			}
			
			uploadContainer.append(uploadForm);

			if(initValue.length >= 1) {
				initValue=initValue.sort();
				for(var i=0;i<initValue.length;i++) {
					thisObj.imagePreview(fileInputName,initValue[i],isMulti,uploadButton,uploadForm,uploadContainer,type);
				}
			}

			thisObj.find('div[role="myupload-file-input-btn"]').click(function(){
				imageEdit = null;
				uploadForm.find('input[type="file"]').val('').trigger("click");
			});

			uploadForm.find('input[type="file"]').change(function(){
				
				//显示上传进度对话框
				thisObj.showUploadDig();
				
				uploadForm.ajaxSubmit({
						url:uploadPath,
						dataType: "json",
						async:true,
						success : function(data,status){
							$('#upload_progress .progress_txt').text('0%');
							$("#upload_progress_val").css('width','0%');							
							layer.close(percentlayer);
							if(data.status==0){
								
								$.each(data.data, function(i,n) {
									if(imageEdit) {
										imageEdit.find('input[role="myupload-picture-input"]').val(n);
										if(type=='image' || type=='face'){
											imageEdit.find('img[role="myupload-picture-show"]').attr("src",n);
										}											
									}else{
										thisObj.imagePreview(fileInputName,n,isMulti,uploadButton,uploadForm,uploadContainer,type);
									}
								});
							}else{
								layer.msg(data.error);
							}
						},
						xhr: function(){
							//页面层-图片
							//上传进度监听
							var xhr = $.ajaxSettings.xhr();
							if(thisObj.onprogress && xhr.upload) {
								xhr.upload.addEventListener("progress" , thisObj.onprogress, false);
								return xhr;
							}
							
						}
				});
				
			})
		},
		//显示上传进度对话框
		showUploadDig:function(){
			var html='<div id="upload_progress">'+
		        '<p class="mb-2 font-weight-bold">上传进度： <span class="float-right progress_txt">0%</span></p>'+
		        '<div class="progress progress-sm">'+
		         '   <div id="upload_progress_val" class="progress-bar" role="progressbar" aria-valuenow="28" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>'+
		        '</div>'+
			'</div>';
			if($("#upload_progress").length<=0){
				$("body").append(html);
			}
			
			//弹出上传提示框
			percentlayer=layer.open({
			  type: 1,
			  title: '正在上传文件,请不要关闭浏览器！',
			  closeBtn:false,
			  area: ['350px','100px'],
			  shadeClose: false,
			  content: $('#upload_progress')
			});
			
		},
		onprogress:function(res){
			// console.log(res);
			var loaded = res.loaded;
			var total = res.total;
			var bfb=(loaded/total*100).toFixed(2);
			console.log(bfb);
			$('#upload_progress .progress_txt').text(bfb+'%');
			$("#upload_progress_val").css('width',bfb+'%');
		},
		imagePreview : function(p,d,i,b,f,c,type) {
			if(i){
				mu='[]';
			}else{
				mu='';
			}
			
			if(type=='file' || type=='audio' || type=='video'){
				
				var imagePreview = $('<div class="myupload_box">' + 
						'<input type="text" class="form-control" name="' + p + mu+'" role="myupload-picture-input" value=""/>' +
            			'<span class="controllbar"><a href="javascript:;" class="btn btn-danger btn-sm cancel" style="width:100%;">删除</a></span></div>');
			}else{
				
				var imagePreview = $('<div class="myupload_box">' + 
	            			'<a href="javascript:;" class="preview_thumb"><img src="#" title="点击可以放大" role="myupload-picture-show" class="preview_img" /></a>' +
	            			'<span class="controllbar"><a href="javascript:;" class="btn btn-danger btn-sm cancel" style="width:100%;">删除</a><input type="text" name="' + p + mu+ '" role="myupload-picture-input" value="" style="display:none;"/></span></div>');				
			}
			
			imagePreview.find('.upload').click(function() {
				imageEdit = $(this).parent().parent().parent();
				f.find('input[type="file"]').val('').trigger("click");
			});
			
			imagePreview.find('.cancel').click(function() {
				$(this).parent().parent().remove();
				if(!i) {
					b.show();
				}
			});
			
			imagePreview.find('input[role="myupload-picture-input"]').val(d);
			
			if(type=='image' || type=='face'){
				imagePreview.find('img[role="myupload-picture-show"]').attr("src",d);
			}			
			
			if(!i) {
				b.hide();
			}
			c.prepend(imagePreview);
		}
	})
})(jQuery);